package org.wisdom.sso.boe.controller;

import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * 用户登陆接口
 *
 * @author zhangzhiyan
 * @date 2021/11/10 14:56
 **/
@Controller
@Slf4j
public class SsoLoginController {

    @Value("${sso.uri}")
    private String ssoUri;

    @Value("${sso.loginUri}")
    private String loginUri;

    @Value("${sso.validateUri}")
    private String validateUri;

    @Value("${service.uri}")
    private String serviceUri;

    @Value("${boe.uri}")
    private String boeUri;

    @GetMapping("/")
    public String index(@RequestParam(value = "ticket", required = false) String ticket, Model model) {
        URLEncoder urlEncoder = new URLEncoder();
        String url = this.ssoUri + this.loginUri;
        model.addAttribute("ssoLoginUrl", url);
        model.addAttribute("boeUrl", this.boeUri);
        model.addAttribute("service", this.serviceUri);
        model.addAttribute("isLogin", false);
        if (!ObjectUtil.isEmpty(ticket)) {
            // 验证ticket
            HttpClient httpClient = HttpClients.createDefault();
            try {
                // 创建HttpClientBuilder
                HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//                closeableHttpClient = httpClientBuilder.build();
                URIBuilder builder = new URIBuilder(this.ssoUri + this.validateUri);
                builder.setParameter("format", "json");
                builder.setParameter("service", this.serviceUri);
                builder.setParameter("ticket", ticket);
                HttpGet httpGet = new HttpGet(builder.build());
                HttpResponse httpResponse;
                HttpEntity entity;
//                httpResponse = closeableHttpClient.execute(httpGet);
                httpResponse = httpClient.execute(httpGet);
                entity = httpResponse.getEntity();

                if (entity != null) {
                    String result = EntityUtils.toString(entity);
                    JSONObject jsonObject = JSONUtil.parseObj(result);
                    System.out.println(jsonObject.toJSONString(2));
                    if (!jsonObject.isNull("serviceResponse")) {
                        JSONObject serviceResponse = jsonObject.getJSONObject("serviceResponse");
                        if (!serviceResponse.isNull("authenticationSuccess")) {
                            model.addAttribute("isLogin", true);
                            model.addAttribute("userName",
                                    serviceResponse.getJSONObject("authenticationSuccess").getStr("user"));
                        }
                    }
                }
//                // 关闭连接
//                closeableHttpClient.close();
            } catch (RuntimeException | URISyntaxException | IOException e) {
                e.printStackTrace();
            }
        }
        return "user";
    }

    @GetMapping("/user")
    public String user(ModelMap modelMap) {
        modelMap.addAttribute("user", "authentication");
        return "user";
    }
}
